package com.wgz.flag.controller;

import com.wgz.flag.common.Result;
import com.wgz.flag.domain.dto.ContactDto;
import com.wgz.flag.domain.dto.ContactRequestDto;
import com.wgz.flag.domain.vo.ContactVo;
import com.wgz.flag.domain.vo.FriendRequestVo;
import com.wgz.flag.service.ContactService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = {"http://localhost:8081","http://localhost:8082"}, allowCredentials = "true")
@RestController
@RequestMapping("/contacts")
@RequiredArgsConstructor
public class ContactController {

    private final ContactService contactService;

    /**
     * 根据用户id获取联系人列表
     * 
     * @param userId 用户id
     * @return 联系人列表
     */
    @GetMapping("/list")
    public Result<List<ContactVo>> getContactList(@RequestParam Long userId) {
        List<ContactVo> contacts = contactService.getContactList(userId);
        return Result.success(contacts);
    }

    /**
     * 添加联系人
     * 
     * @param userId     用户id
     * @param contactDto 联系人信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result<String> addContact(@RequestParam Long userId, @RequestBody ContactDto contactDto) {
        contactService.addContact(userId, contactDto);
        return Result.success("添加成功");
    }

    /**
     * 更新联系人信息
     * 
     * @param userId     用户id
     * @param friendId   联系人id
     * @param contactDto 更新的联系人信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<String> updateContact(
            @RequestParam Long userId,
            @RequestParam Long friendId,
            @RequestBody ContactDto contactDto) {
        contactService.updateContact(userId, friendId, contactDto);
        return Result.success("更新成功");
    }

    /**
     * 删除联系人
     * 
     * @param userId   用户id
     * @param friendId 联系人id
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public Result<String> deleteContact(@RequestParam Long userId, @RequestParam Long friendId) {
        contactService.deleteContact(userId, friendId);
        return Result.success("删除成功");
    }

    @PostMapping("/request")
    public Result<String> sendFriendRequest(
            @RequestParam Long userId,
            @RequestBody ContactRequestDto requestDto) {
        contactService.sendFriendRequest(userId, requestDto);
        return Result.success("好友请求已发送");
    }

    @GetMapping("/requests")
    public Result<List<FriendRequestVo>> getPendingRequests(@RequestParam Long userId) {
        return Result.success(contactService.getPendingRequests(userId));
    }

    @PostMapping("/request/handle")
    public Result<String> handleFriendRequest(
            @RequestParam Long userId,
            @RequestParam Long requestId,
            @RequestParam Boolean accept) {
        contactService.handleFriendRequest(userId, requestId, accept);
        return Result.success(accept ? "已添加好友" : "已拒绝请求");
    }
}